#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtQml>
#include <QSurfaceFormat>
#include <QDebug>
#include <QCoreApplication>
#include "memostorage.h"

extern "C" int qtmain(int argc, char **argv)
{
    qDebug() << "开始初始化备忘录应用...";
    
    // 在创建应用前设置使用 OpenGL ES（HarmonyOS需要）
    QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);
    QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
    
    // 模拟器兜底：强制使用 Qt Quick 软件后端（如果硬件加速失败）
    qputenv("QT_QUICK_BACKEND", "software");
    qputenv("QSG_RENDER_LOOP", "basic");
    
    // 配置 OpenGL ES 表面格式
    QSurfaceFormat format;
    format.setAlphaBufferSize(8);
    format.setRedBufferSize(8);
    format.setGreenBufferSize(8);
    format.setBlueBufferSize(8);
    format.setDepthBufferSize(24);
    format.setStencilBufferSize(8);
    format.setRenderableType(QSurfaceFormat::OpenGLES);
    format.setVersion(2, 0);
    format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
    format.setSamples(0);
    QSurfaceFormat::setDefaultFormat(format);
    qDebug() << "OpenGL ES版本:" << format.majorVersion() << "." << format.minorVersion();
    
    QGuiApplication app(argc, argv);
    QCoreApplication::setApplicationName("备忘录");
    QCoreApplication::setOrganizationName("MemoApp");
    QCoreApplication::setOrganizationDomain("memoapp.com");
    
    // 注册MemoStorage到QML
    qmlRegisterType<MemoStorage>("MemoApp", 1, 0, "MemoStorage");
    
    QQmlApplicationEngine engine;
    
    // 创建MemoStorage实例并设置为上下文属性
    MemoStorage *memoStorage = new MemoStorage(&app);
    engine.rootContext()->setContextProperty("memoStorage", memoStorage);
    
    // 连接QML错误信号以便调试
    QObject::connect(&engine, &QQmlApplicationEngine::warnings, [](const QList<QQmlError> &warnings) {
        for (const auto &warning : warnings) {
            qWarning() << "QML警告:" << warning.toString();
        }
    });
    
    qDebug() << "加载QML文件...";
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    
    if (engine.rootObjects().isEmpty()) {
        qCritical() << "QML加载失败，尝试加载备用界面...";
        // 加载备用界面
        static const char fallbackQml[] =
            "import QtQuick 2.15\n"
            "import QtQuick.Controls 2.15\n"
            "Rectangle {\n"
            "  width: 480; height: 320; color: \"#f8fafc\"\n"
            "  Column {\n"
            "    anchors.centerIn: parent\n"
            "    spacing: 20\n"
            "    Text { \n"
            "      anchors.horizontalCenter: parent.horizontalCenter\n"
            "      color: \"#ef4444\"; \n"
            "      text: \"QML加载失败\"; \n"
            "      font.pixelSize: 20 \n"
            "    }\n"
            "    Text {\n"
            "      anchors.horizontalCenter: parent.horizontalCenter\n"
            "      color: \"#64748b\";\n"
            "      text: \"请检查日志信息\";\n"
            "      font.pixelSize: 14\n"
            "    }\n"
            "  }\n"
            "}\n";
        engine.loadData(QByteArray(fallbackQml), QUrl(QStringLiteral("qrc:/fallback.qml")));
        if (engine.rootObjects().isEmpty()) {
            qCritical() << "备用界面也加载失败，退出应用";
            return -1;
        }
    } else {
        qDebug() << "QML文件加载成功";
    }
    
    qDebug() << "备忘录应用启动成功，进入事件循环";
    return app.exec();
}

// HarmonyOS兼容性：提供main函数入口
extern "C" int main(int argc, char **argv)
{
    return qtmain(argc, argv);
}